//
//  FlyFindCarViewController.m
//  JiongTu
//
//  Created by Dupengfei on 16/3/15.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

//输入框总高度
#define INPUT_H 260
//减去导航栏与状态栏的屏幕高度
#define SCREEN_H [UIScreen mainScreen].bounds.size.height - 64
//最大输入字符数
#define MAX_LIMIT_NUMS 20

#import "JTConst.h"
#import "FlyFindCarViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <SVProgressHUD.h>
#import <AVOSCloud.h>

#import "OrderShowViewController.h"
#import "JTBaseNaviController.h"
#import "JTProvisionViewController.h"

#import "JTDatePicker.h"
#import "JTLocationPicker.h"
#import "JTTimePicker.h"
#import "FindCar.h"
#import "JTUser.h"
#import "JTPassengerTrip.h"

NSString * const KVO_Start = @"startLocation.text";
NSString * const KVO_End = @"endLocation.text";
NSString * const KVO_Num = @"count";

@interface FlyFindCarViewController ()<CLLocationManagerDelegate,UIScrollViewDelegate, UITextViewDelegate>
{
    CLLocationManager *_locationManager;
}
@property (weak, nonatomic) IBOutlet UITextField *startLocation;
@property (weak, nonatomic) IBOutlet UITextField *startStreet;
@property (weak, nonatomic) IBOutlet UIButton *findCarAgree;
@property (weak, nonatomic) IBOutlet UITextField *endLocation;
@property (weak, nonatomic) IBOutlet UITextField *endStreet;
@property (weak, nonatomic) IBOutlet UIButton *numberOfPeopleMinus;
@property (weak, nonatomic) IBOutlet UIButton *numberOfPeoplePlus;
@property (weak, nonatomic) IBOutlet UIButton *findCarButton;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak , nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *agreeButton;
@property (weak, nonatomic) IBOutlet UILabel *numberOfPeople;
@property (weak, nonatomic) IBOutlet UITextField *timeOfGo;
@property (weak, nonatomic) IBOutlet UITextField *timeInterval;

@property (weak, nonatomic) IBOutlet UIView *markView;

@property (nonatomic, assign) int number;
@property (nonatomic, assign) BOOL open;
@property (nonatomic, strong) NSString * objectNewId;
@property (nonatomic, strong) UIPickerView * pickerView;
@property (nonatomic, strong) NSDictionary * dic;
@property (nonatomic, strong) NSArray * array;
@property (nonatomic, strong) NSArray * locatonArray;
@property (nonatomic, strong) NSString * city;
@property (nonatomic, strong) NSString * country;

@property (nonatomic, strong) NSDictionary *priceDict;
@property (nonatomic, assign) NSUInteger tripPrice;
@property (nonatomic, assign) NSUInteger count;

/**
 *  键盘附加显示view
 */
@property (nonatomic, strong) UIToolbar *kbAccessory;

@end

@implementation FlyFindCarViewController

- (NSDictionary *)priceDict {
    if (!_priceDict) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Price" ofType:@"plist"];
        _priceDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    }
    return _priceDict;
}

- (UIToolbar *)kbAccessory {
    if (!_kbAccessory) {
        _kbAccessory = [[UIToolbar alloc] init];
        _kbAccessory.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"确定"
                                                                  style:UIBarButtonItemStyleDone
                                                                 target:self
                                                                 action:@selector(btnPressed:)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                               target:nil
                                                                               action:nil];
        _kbAccessory.items = [NSArray arrayWithObjects:space, right, nil];
    }
    return _kbAccessory;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.count = 1;
    
    [self initializeInterface];
    
    [self initializeLocationService];
    
    [self addObserver:self forKeyPath:KVO_Start options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:KVO_End options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:KVO_Num options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:nil];
    
    if (self.sameTrip) {
        [self sameFind];
    }
}

- (void)dealloc {
    [self removeObserver:self forKeyPath:KVO_Start];
    [self removeObserver:self forKeyPath:KVO_End];
    [self removeObserver:self forKeyPath:KVO_Num];
}

-(void)initializeInterface
{
    _open = NO;
    
    _scrollView.delegate = self;
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchScrollView)];
    [recognizer setNumberOfTapsRequired:1];
    
    [recognizer setNumberOfTouchesRequired:1];
    
    [self.scrollView addGestureRecognizer:recognizer];
    
    self.view.backgroundColor =[UIColor whiteColor];
    
    self.navigationItem.title = @"查找车";
    
    self.textView.delegate = self;
    
    _timeOfGo.inputView = [JTDatePicker sharedPicker];
    self.timeOfGo.inputAccessoryView = self.kbAccessory;
    
    self.timeInterval.inputView = [JTTimePicker sharedPicker];
    self.timeInterval.inputAccessoryView = self.kbAccessory;
    
    self.startLocation.inputView = [JTLocationPicker sharedPicker];
    self.startLocation.inputAccessoryView = self.kbAccessory;
    self.endLocation.inputView = [JTLocationPicker sharedPicker];
    self.endLocation.inputAccessoryView = self.kbAccessory;
    
}

- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    // 取得定位权限，有两个方法，取决于你的定位使用情况
    // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
}

- (void)sameFind {
    self.startLocation.text = self.sameTrip.startLocation;
    self.startStreet.text = self.sameTrip.startStreet;
    self.endLocation.text = self.sameTrip.endLocation;
    self.endStreet.text = self.sameTrip.endStreet;
    self.timeOfGo.text = self.sameTrip.time;
    self.timeInterval.text = self.sameTrip.timeInterval;
    self.count = [self.sameTrip.orderSeatNumber unsignedIntegerValue];
    self.textView.text = self.sameTrip.remark;
}

#pragma mark - delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取当前所在的地理位置街道
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array){
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            NSString *city = [NSString stringWithFormat:@"%@%@", placemark.addressDictionary[@"City"], placemark.addressDictionary[@"SubLocality"]];
            self.startLocation.text = city;
            NSString *street = [NSString stringWithFormat:@"%@", placemark.addressDictionary[@"Street"]];
            self.startStreet.text = street;
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

#pragma mark - TextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
    //文本框最下端在当前屏幕中的位置
    CGFloat textMaxY = CGRectGetMaxY(textView.frame) + CGRectGetMinY(self.markView.frame) - self.scrollView.contentOffset.y;
    //如果被键盘遮挡
    if (textMaxY > (SCREEN_H - INPUT_H)) {
        CGFloat nowY = self.scrollView.contentOffset.y;
        //上移的高度
        nowY += textMaxY - (SCREEN_H - INPUT_H);
        [UIView animateWithDuration:0.25 animations:^{
            self.scrollView.contentOffset = CGPointMake(0, nowY);
        }];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    //获取高亮部分内容
    //NSString * selectedtext = [textView textInRange:selectedRange];
    
    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        if (offsetRange.location < MAX_LIMIT_NUMS) {
            return YES;
        }
        else
        {
            [SVProgressHUD showInfoWithStatus:@"超出最大长度"];
            return NO;
        }
    }
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = @"";
            //判断是否只普通的字符或asc码(对于中文和表情返回NO)
            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
            if (asc) {
                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
            }
            else
            {
                __block NSInteger idx = 0;
                __block NSString  *trimString = @"";//截取出的字串
                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个
                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                                         options:NSStringEnumerationByComposedCharacterSequences
                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                                          
                                          if (idx >= rg.length) {
                                              *stop = YES; //取出所需要就break，提高效率
                                              return ;
                                          }
                                          
                                          trimString = [trimString stringByAppendingString:substring];
                                          
                                          idx++;
                                      }];
                
                s = trimString;
            }
            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            //既然是超出部分截取了，哪一定是最大限制了。
//            self.lbNums.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
            NSLog(@"%@", [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS]);
        }
        [SVProgressHUD showInfoWithStatus:@"超出最大长度"];
        return NO;
    }
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果在变化中是高亮部分在变，就不要计算字符了
    if (selectedRange && pos) {
        return;
    }
    
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > MAX_LIMIT_NUMS)
    {
        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        
        [textView setText:s];
    }
    
    //不让显示负数 口口日
//    self.lbNums.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
//    NSLog(@"%@", [NSString stringWithFormat:@"%d/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS]);
}

#pragma mark - 交互事件
//乘客人数减
- (IBAction)minusButtonPressed:(UIButton *)sender {
    if (self.count > 1) {
        self.count--;
    }
}
//乘客人数加
- (IBAction)plusButtonPressed:(UIButton *)sender {
    
    if (self.count < 4) {
        self.count++;
    }
}
//查找车按钮
- (IBAction)findCarButtonPressed:(UIButton *)sender {
    
    if([_startLocation.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"出发地不能为空"];
    } else if ([_endLocation.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"目的地不能为空"];
    } else if  (!self.agreeButton.isSelected) {
        [SVProgressHUD showInfoWithStatus:@"请同意条款"];
    } else if  ([self.timeOfGo.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"预约时间为空"];
    } else if ([self.timeInterval.text compare:@"06时00分"] == -1) {
        [SVProgressHUD showInfoWithStatus:@"时间不在范围内"];
    } else if (self.tripPrice == 0) {
        [SVProgressHUD showInfoWithStatus:@"您选择的线路未开通"];
    } else {
        
        JTPassengerTrip *oneTrip = [[JTPassengerTrip alloc] init];
        oneTrip.startLocation = self.startLocation.text;
        oneTrip.startStreet= self.startStreet.text;
        oneTrip.endLocation = self.endLocation.text;
        oneTrip.endStreet = self.endStreet.text;
        oneTrip.time = self.timeOfGo.text;
        oneTrip.timeInterval = self.timeInterval.text;
        oneTrip.orderSeatNumber = @([self.numberOfPeople.text intValue]);
        oneTrip.passenger = [AVUser currentUser];
        oneTrip.price = @(self.tripPrice * self.count);
        oneTrip.identity = @"乘客";
        oneTrip.remark = self.textView.text;
        oneTrip.start =[self.startLocation.text substringToIndex:3];
        oneTrip.end =[self.endLocation.text substringToIndex:3];
        
        if (self.sameTrip) {
            //先删除之前的一单
            AVQuery * query = [AVQuery queryWithClassName:kJTClassJourneyPassenger];
            [query whereKey:@"objectId" equalTo:self.sameTrip.objectId];
            [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                [object deleteInBackground];
            }];
            //然后再进行发布
            AVQuery * newTripQuery = [AVQuery queryWithClassName:kJTClassPassenger];
            [newTripQuery whereKey:kJTPassengerKeyId equalTo:[AVUser currentUser].objectId];
            [newTripQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                if (object) {
                    [FindCar passenger:object find:oneTrip];
                }
                else {
                    [FindCar firstFind:oneTrip];
                }
            
                
            }];
        } else {
            AVQuery * query = [AVQuery queryWithClassName:kJTClassPassenger];
            [query whereKey:kJTPassengerKeyId equalTo:[AVUser currentUser].objectId];
            [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                if (object) {
                    [FindCar passenger:object find:oneTrip];
                }
                else {
                    [FindCar firstFind:oneTrip];
                }
                
            }];
        }
        
        OrderShowViewController * VC = [[OrderShowViewController alloc]init];
        VC.oneTrip = oneTrip;
        JTBaseNaviController *navi = [JTBaseNaviController navigationControllerWithRootViewController:VC];
        [self presentViewController:navi animated:YES completion:^{
            [self.navigationController popToRootViewControllerAnimated:NO];
        }];
    }
}

- (IBAction)startLocation:(id)sender {
    self.startLocation.text = @"正在定位中";
    
    [_locationManager startUpdatingLocation];
}

//拼车条约
- (IBAction)findCarAgree:(UIButton *)sender
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    JTProvisionViewController *proVC = [sb instantiateViewControllerWithIdentifier:@"provision"];
    proVC.provisionName = @"Provision_Passenger";
    JTBaseNaviController *navi = [JTBaseNaviController navigationControllerWithRootViewController:proVC];
    [self presentViewController:navi animated:YES completion:nil];
}
//同意按钮
- (IBAction)agrrePressed:(UIButton *)sender
{
   
    sender.selected = !sender.isSelected;
}

#pragma mark - 回收键盘
- (void)touchScrollView
{
    [self.startLocation resignFirstResponder];
    [self.startStreet resignFirstResponder];
    [self.endLocation resignFirstResponder];
    
    [self.startStreet resignFirstResponder];
    
    [self.endStreet resignFirstResponder];
    
    [self.textView resignFirstResponder];
    
    [self.timeOfGo resignFirstResponder];
    
}

- (void)btnPressed:(id)sender {
    
    if (self.startLocation.editing) {
        self.startLocation.text = [JTLocationPicker sharedPicker].cityAndSubloca;
    } else if (self.endLocation.editing) {
        self.endLocation.text = [JTLocationPicker sharedPicker].cityAndSubloca;
    } else if (self.timeOfGo.editing) {
        NSDate *selectedDate = [JTDatePicker sharedPicker].date;
        
        //使用日期格式器可以将时区忽略
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
        dateFormatter.dateFormat=@"yyyy年MM月dd日";
        NSString *dateStr = [dateFormatter stringFromDate:selectedDate];
        self.timeOfGo.text = dateStr;
        
        NSDateFormatter *timeFormatter=[[NSDateFormatter alloc]init];
        timeFormatter.dateFormat=@"HH时mm分";
        NSString *timeStr = [timeFormatter stringFromDate:selectedDate];
        self.timeInterval.text = timeStr;
        
        //选择完日期后改变时间选择器内容
        self.timeInterval.inputView = [JTTimePicker pickerWithDate:selectedDate];
        
    } else if (self.timeInterval.editing) {
        JTTimePicker *picker = self.timeInterval.inputView;
        NSDate *selectedDate = picker.date;
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"HH时mm分";
        NSString *timeStr=[formatter stringFromDate:selectedDate];
        self.timeInterval.text = timeStr;
    }
    
    [self.timeOfGo endEditing:YES];
    [self.timeInterval endEditing:YES];
    [self.startLocation endEditing:YES];
    [self.endLocation endEditing:YES];
    
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:KVO_End]) {
        [self calculatePrice:change[@"new"] withOtherLocation:self.startLocation.text number:[self.numberOfPeople.text integerValue]];
    } else if ([keyPath isEqualToString:KVO_Start]) {
        NSLog(@"%@", change);
        [self calculatePrice:change[@"new"] withOtherLocation:self.endLocation.text number:[self.numberOfPeople.text integerValue]];
    }
    
    if ([keyPath isEqualToString:KVO_Num]) {
        self.numberOfPeople.text = [NSString stringWithFormat:@"%@", change[@"new"]];
//        NSLog(@"%d", [change[@"new"] unsignedIntegerValue] * self.tripPrice);
    }
}

/**
 *  计算两个文本框中位置的价钱
 */
- (void)calculatePrice:(NSString *)location withOtherLocation:(NSString *)other number:(NSUInteger)number {
    //正在编辑文本框的城市
    NSString *startCity = [NSString string];
    if (![location isEqualToString:@""]) {
        startCity = [location substringToIndex:3];
    }
    //另外一个文本框的城市
    NSString *endCity = [NSString string];
    if (![other isEqualToString:@""]) {
        endCity = [other substringToIndex:3];
    }
    //以另外一个文本框的成都为起点
    if ([endCity isEqualToString:@"成都市"]) {
        //如果正在编辑的文本框存在对应的项目
        if (self.priceDict[startCity]) {
            if (self.priceDict[location]) {
                self.tripPrice = [self.priceDict[location] unsignedIntegerValue];
//                NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
            } else {
                self.tripPrice = [self.priceDict[startCity] unsignedIntegerValue];
//                NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
            }
        } else {
            self.tripPrice = 0;
//            NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
        }
        //以正在编辑的文本框的成都为起点
    } else if ([startCity isEqualToString:@"成都市"]) {
        if (self.priceDict[endCity]) {
            if (self.priceDict[other]) {
                self.tripPrice = [self.priceDict[other] unsignedIntegerValue];
//                NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
            } else {
                self.tripPrice = [self.priceDict[endCity] unsignedIntegerValue];
//                NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
            }
        } else {
            self.tripPrice = 0;
//            NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
        }
        //两个文本框都不以成都为起点，则费用为0
    } else {
        self.tripPrice = 0;
//        NSLog(@"%@", [NSString stringWithFormat:@"%u元", (self.tripPrice * number)]);
    }
}

@end
